import { Button, message, Space } from 'antd';
import { IAuthRoleGranBtn } from '../../type';
import cls from 'classnames';
import { useContext } from 'react';
import { AuthorizationContext } from '../AuthHooks';
import { useRequest } from 'umi';
import { requestFunCompon } from '@/utils';

export const AuthRoleGranBtn: React.FC<IAuthRoleGranBtn> = ({
  roleInfo,
  reloadRoleDetail,
}) => {
  const {
    prefixCls,
    stepsIndex,
    authGranDispatch,
    leftSelectKeys,
    secondSaveIdList,
    threeSaveIdList,
    roleAuthDetailInfo,
  } = useContext(AuthorizationContext); //获取 上下文

  // 上一步下一步改变
  const changeSteps = (stepType: string) => {
    let steps: number = stepsIndex;
    if (stepType == 'prev') {
      authGranDispatch({
        type: 'authGran-stepsIndex',
        payload: steps - 1,
      });
      // changeStepsSave(steps - 1)
    }

    if (stepType == 'next') {
      if (leftSelectKeys && leftSelectKeys?.length > 0) {
        authGranDispatch({
          type: 'authGran-stepsIndex',
          payload: steps + 1,
        });
      } else {
        message.warning(
          '请选择至少一个及以上的资源目录，才可进行下一步的授权操作！',
        );
      }

      // changeStepsSave(steps + 1)
    }
  };

  // 上一步下一步保存参数
  // const changeStepsSave = (steps: number) => {
  //   authGranDispatch({
  //     type: 'authGran-firstLeftTreeKeys',
  //     paylaod: leftSelectKeys
  //   })
  //   authGranDispatch({
  //     type: 'authGran-firstRightListRows',
  //     paylaod: leftTreeCheckRows
  //   })

  // }

  // 保存
  const saveAuthRole = () => {
    let secondIDArr: any[] = [];
    if (secondSaveIdList == null) {
      roleAuthDetailInfo?.paramObject?.scope?.map((item: any) => {
        secondIDArr?.push(item?.id);
      });
    } else {
      secondIDArr = secondSaveIdList;
    }
    let threeIDArr: any[] = [];
    if (threeSaveIdList == null) {
      roleAuthDetailInfo?.paramObject?.handle?.map((item: any) => {
        threeIDArr?.push(item?.id);
      });
    } else {
      threeIDArr = threeSaveIdList;
    }

    let resourceIds = [...leftSelectKeys, ...secondIDArr, ...threeIDArr];
    grantRoleCont?.run(resourceIds);
  };

  // 授权操作
  const grantRoleCont = useRequest(
    (resourceIdList: string[]) => {
      let bodyParams = {
        resourceIds:
          resourceIdList?.length > 0 ? resourceIdList?.toString() : null,
        id: roleInfo?.id,
        versionNum: roleInfo?.versionNum,
      };
      let reqUrl = `/roleController/grant`;
      return requestFunCompon('PUT', reqUrl, bodyParams);
    },
    {
      manual: true,
      onSuccess(data: any, params: any): void {
        if (data && data?.msgFlag) {
          message.success(data?.msg);
          reloadRoleDetail();
        } else {
          message.error(data?.msg);
        }
      },
    },
  );

  return (
    <>
      <div className={cls(prefixCls + 'role-ColBottom')}>
        <div className={cls(prefixCls + 'divBox', prefixCls + 'colBottom-div')}>
          <Space>
            {stepsIndex != 0 && (
              <Button
                onClick={() => {
                  changeSteps('prev');
                }}
                type={'primary'}
                onMouseOut={(event: any) => {
                  event?.target?.nodeName == 'BUTTON'
                    ? event?.target?.blur()
                    : event?.target?.parentNode?.blur();
                }}
                loading={grantRoleCont?.loading}
              >
                上一步
              </Button>
            )}

            {stepsIndex != 2 && (
              <Button
                onClick={() => {
                  changeSteps('next');
                }}
                type={'primary'}
                onMouseOut={(event: any) => {
                  event?.target?.nodeName == 'BUTTON'
                    ? event?.target?.blur()
                    : event?.target?.parentNode?.blur();
                }}
                loading={grantRoleCont?.loading}
              >
                下一步
              </Button>
            )}

            <Button
              onClick={() => {
                saveAuthRole();
              }}
              type={'primary'}
              onMouseOut={(event: any) => {
                event?.target?.nodeName == 'BUTTON'
                  ? event?.target?.blur()
                  : event?.target?.parentNode?.blur();
              }}
              loading={grantRoleCont?.loading}
            >
              保存
            </Button>
          </Space>
        </div>
      </div>
    </>
  );
};
